package com.prs.crm.action.project;

import java.io.File;
import java.util.Collection;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.courser.struts.BaseAction;
import org.courser.ui.PaginationSupport;
import org.courser.ui.TreeNode;
import org.hibernate.criterion.DetachedCriteria;

import com.prs.crm.annotation.Clew;
import com.prs.crm.context.AppContext;
import com.prs.crm.domain.Attachment;
import com.prs.crm.domain.project.ProjectStage;
import com.prs.crm.domain.project.Task;
import com.prs.crm.domain.project.TaskAttach;
import com.prs.crm.exception.InValidException;
import com.prs.crm.service.project.ProjectStageService;
import com.prs.crm.service.project.TaskService;

public class TaskAction extends BaseAction {

	private static final long serialVersionUID = 2929208923967070248L;

	private TaskService taskService;

	private ProjectStageService projectStageService;

	private Collection<ProjectStage> stagelist;

	private Boolean endTask;

	private TaskAttach taskAttach;

	private Task task;

	private Task parentTask;

	private TreeNode taskNode;

	private PaginationSupport pagination;

	private Attachment attachment;

	private File upload;

	private String uploadFileName;

	private String joiner;

	private File[] uploads;

	private String[] uploadsFileName;

	private Integer[] attachIds;

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setProjectStageService(ProjectStageService projectStageService) {
		this.projectStageService = projectStageService;
	}

	public ProjectStageService getProjectStageService() {
		return projectStageService;
	}

	public void setAttachment(Attachment attachment) {
		this.attachment = attachment;
	}

	public Attachment getAttachment() {
		return attachment;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	public Task getTask() {
		return task;
	}

	public void setPagination(PaginationSupport pagination) {
		this.pagination = pagination;
	}

	public PaginationSupport getPagination() {
		return pagination;
	}

	public void setUpload(File upload) {
		this.upload = upload;
	}

	public File getUpload() {
		return upload;
	}

	public void setUploadFileName(String uploadFileName) {
		this.uploadFileName = uploadFileName;
	}

	public String getUploadFileName() {
		return uploadFileName;
	}

	public void setParentTask(Task parentTask) {
		this.parentTask = parentTask;
	}

	public Task getParentTask() {
		return parentTask;
	}

	/**
	 * @param stagelist
	 *            the stagelist to set
	 */
	public void setStagelist(Collection<ProjectStage> stagelist) {
		this.stagelist = stagelist;
	}

	/**
	 * @return the stagelist
	 */
	public Collection<ProjectStage> getStagelist() {
		return stagelist;
	}

	public void setEndTask(Boolean endTask) {
		this.endTask = endTask;
	}

	public Boolean getEndTask() {
		return endTask;
	}

	public void setTaskNode(TreeNode taskNode) {
		this.taskNode = taskNode;
	}

	public TreeNode getTaskNode() {
		return taskNode;
	}

	public void setJoiner(String joiner) {
		this.joiner = joiner;
	}

	public String getJoiner() {
		return joiner;
	}

	public void setUploads(File[] uploads) {
		this.uploads = uploads;
	}

	public File[] getUploads() {
		return uploads;
	}

	public void setTaskAttach(TaskAttach taskAttach) {
		this.taskAttach = taskAttach;
	}

	public TaskAttach getTaskAttach() {
		return taskAttach;
	}

	public void setAttachIds(Integer[] attachIds) {
		this.attachIds = attachIds;
	}

	public Integer[] getAttachIds() {
		return attachIds;
	}

	public void setUploadsFileName(String[] uploadsFileName) {
		this.uploadsFileName = uploadsFileName;
	}

	public String[] getUploadsFileName() {
		return uploadsFileName;
	}

	/**
	 * 列出当前我执行的任务
	 * 
	 * @return
	 */
	@Action("listExecuteTask")
	public String listExecuteTask() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Task.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getTaskService().listExecuteTask(criteria,
				pagination, AppContext.getAccountContext().currentUser()));
		return SUCCESS;
	}

	/**
	 * 列出我的任务以方便分解
	 * 
	 * @return
	 */
	@Action("listMyTask")
	public String listMyTask() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Task.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getTaskService().listExecuteTask(criteria,
				pagination, AppContext.getAccountContext().currentUser()));
		return SUCCESS;
	}

	@Action("listInValidTask")
	public String listInValidTask() {
		DetachedCriteria criteria = this.getPaginationHelper().createQuery(
				Task.class);
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getTaskService().listInValidTask(criteria,
				pagination, AppContext.getAccountContext().currentUser()));
		return SUCCESS;
	}

	/**
	 * 任务执行
	 * 
	 * @return
	 */
	@Action("executeTask")
	public String executeTask() {
		this.setStagelist(this.getProjectStageService().getAllStage());
		pagination = this.getPaginationHelper().prepare(pagination);
		this.setPagination(this.getTaskService().listTaskReports(pagination,
				task));
		return SUCCESS;
	}

	@Action("createTaskAttach")
	public String createTaskAttach() {
		return SUCCESS;
	}

	@Action("listTaskReports")
	public String listTaskReports() {
		return this.viewTaskReports();
	}

	@Action("viewTaskReports")
	public String viewTaskReports() {
		this.setPagination(this.getTaskService().listTaskReports(
				this.getPaginationHelper().prepare(pagination, 5), task));
		return SUCCESS;
	}

	@Action("editTaskAttach")
	public String editTaskAttach() {
		this.setTask(this.getTaskAttach().getTask());
		return SUCCESS;
	}

	@Action(value = "submitTaskAttach", results = {
			@Result(name = "success", type = "redirect", location = "executeTask?task=${task.id}"),
			@Result(name = "error", type = "chain", location = "createTaskAttach") })
	public String submitTaskAttach() {
		try {
			this.getTaskService().submitTaskAttach(task, taskAttach, upload,
					uploadFileName);
			return SUCCESS;
		} catch (InValidException e) {
			this.addActionError(e.getMessage());
			return ERROR;
		}
	}

	@Action(value = "updateTaskAttach", results = { @Result(name = "success", type = "redirect", location = "executeTask?task=${task.id}") })
	public String updateTaskAttach() {
		this.getTaskService().updateTaskAttach(taskAttach, upload,
				uploadFileName);
		return SUCCESS;
	}

	@Action(value = "removeTaskAttach", results = { @Result(name = "success", type = "redirect", location = "listTaskReports?task=${task.id}") })
	public String removeTaskAttach() {
		this.getTaskService().removeAttachs(attachIds);
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "saveTask", results = {
			@Result(name = "success", type = "redirect", location = "executeTask?task=${task.id}"),
			@Result(name = "error", type = "chain", location = "executeTask") })
	public String saveTask() {
		try {
			this.getTaskService().save(task);

			this.setPrompt("保存成功");
			return SUCCESS;
		} catch (InValidException e) {
			this.addActionError(e.getMessage());
			return ERROR;
		}
	}

	@Action("childTask")
	public String childTask() {
		return SUCCESS;
	}

	@Action("taskTree")
	public String taskTree() {
		return SUCCESS;
	}

	@Action("viewChildTask")
	public String viewChildTask() {
		return SUCCESS;
	}

	@Action("createChildTask")
	public String createChildTask() {
		return SUCCESS;
	}

	@Clew(results = { "success" })
	@Action(value = "saveChildTask", results = {
			@Result(name = "success", type = "redirect", location = "viewChildTask?task=${task.id}"),
			@Result(name = "error", type = "chain", location = "createChildTask") })
	public String saveChildTask() {
		if (task.getName() == null || "".equals(task.getName().trim())) {
			addActionError("名字不能为空");
			return ERROR;
		}
		if (task.getGrade() == null) {
			addActionError("级别不能为空");
			return ERROR;
		}
		if (task.getCycles() == null) {
			addActionError("周期不能为空");
			return ERROR;
		}
		if (joiner == null || "".equals(joiner.trim())) {
			addActionError("参与人不能为空");
			return ERROR;
		}
		if (task.getStartTime() == null) {
			addActionError("开始时间不能为空");
			return ERROR;
		}
		if (task.getEndTime() == null) {
			addActionError("结束时间不能为空");
			return ERROR;
		}

		try {
			this.getTaskService().createChildTask(task, parentTask, joiner,
					uploads, uploadsFileName);
			this.setPrompt("创建成功");
			return SUCCESS;
		} catch (InValidException e) {
			this.addActionError(e.getMessage());
			return ERROR;
		}
	}

	@Action(value = "removeChildTask", results = { @Result(name = "success", type = "json", params = {
			"root", "prompt" }) })
	public String removeChildTask() {
		try {
			this.getTaskService().removeTask(task);
			this.setPrompt("true");
		} catch (InValidException e) {
			this.setPrompt("false");
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return SUCCESS;
	}

	/**
	 * 任务树
	 * 
	 * @return
	 */
	@Action(value = "loadTaskTree", results = { @Result(name = "success", type = "json", params = {
			"root", "taskNode" }) })
	public String loadTaskTree() {
		taskNode = new TreeNode();
		taskNode.setId("-1");

		TreeNode rootNode = new TreeNode();
		rootNode.setId(task.getId().toString());
		rootNode.setText(task.getName());
		rootNode.setValue(task.getStatus().toString());
		addChildNode(rootNode, task);

		taskNode.addChildNode(rootNode);
		return SUCCESS;
	}

	private void addChildNode(TreeNode parentNode, Task task) {
		if (task.getChildTasks() != null) {
			for (Task childTask : task.getChildTasks()) {
				TreeNode node = new TreeNode();
				node.setId(childTask.getId().toString());
				node.setText(childTask.getName());
				node.setValue(childTask.getStatus().toString());
				parentNode.addChildNode(node);
				addChildNode(node, childTask);
			}
		}
	}

}
